package com.example.gui;

import com.example.dao.UserDAO;
import com.example.model.CardInfo;


import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class UserLoginFrame extends JFrame {
    private JTextField usernameField;
    private JPasswordField passwordField;

    public UserLoginFrame() {
        setTitle("用户登录");
        setSize(350, 250);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setLayout(new BorderLayout());

        // 标题面板
        JPanel titlePanel = new JPanel();
        JLabel titleLabel = new JLabel("系统登录", SwingConstants.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 20));
        titlePanel.add(titleLabel);
        add(titlePanel, BorderLayout.NORTH);

        // 主面板
        JPanel mainPanel = new JPanel(new GridLayout(3, 2, 10, 10));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        JLabel lblUsername = new JLabel("卡号:");
        lblUsername.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        usernameField = new JTextField();

        JLabel lblPassword = new JLabel("密码:");
        lblPassword.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        passwordField = new JPasswordField();

        mainPanel.add(lblUsername);
        mainPanel.add(usernameField);
        mainPanel.add(lblPassword);
        mainPanel.add(passwordField);
        mainPanel.add(new JLabel()); // 占位
        add(mainPanel, BorderLayout.CENTER);

        // 按钮面板
        JPanel buttonPanel = new JPanel();
        JButton btnLogin = new JButton("登录");
        JButton btnCancel = new JButton("取消");

        btnLogin.addActionListener(new LoginButtonListener());
        btnCancel.addActionListener(e -> System.exit(0));

        buttonPanel.add(btnLogin);
        buttonPanel.add(btnCancel);
        add(buttonPanel, BorderLayout.SOUTH);
    }

    private class LoginButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            String cardname = usernameField.getText().trim();
            String password = new String(passwordField.getPassword());

            if (cardname.isEmpty() || password.isEmpty()) {
                JOptionPane.showMessageDialog(UserLoginFrame.this,
                        "卡号和密码不能为空", "输入错误", JOptionPane.WARNING_MESSAGE);
                return;
            }

            UserDAO userDao = new UserDAO();
            CardInfo cardInfo = userDao.cardLogin(cardname, password);
            if (cardInfo != null) {
                // 登录成功，打开欢迎窗口并关闭登录窗口
                new UserMainFrame(cardInfo).setVisible(true);
                UserLoginFrame.this.dispose();
            } else {
                JOptionPane.showMessageDialog(UserLoginFrame.this,
                        "用户名或密码错误", "登录失败", JOptionPane.ERROR_MESSAGE);
                passwordField.setText("");
            }
        }
    }
}